#include "moveablewidget.h"
#include <QPainter>
#include <QDebug>
#include <QMouseEvent>

MoveableWidget::MoveableWidget(QWidget *parent) : QWidget(parent)
{
    m_bCanMove = false;
    setAttribute(Qt::WA_Hover, true);
    setMouseTracking(true);
}

MoveableWidget::~MoveableWidget()
{

}

void MoveableWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter p(this);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::darkMagenta);
    p.drawRect(rect());
}


void MoveableWidget::mousePressEvent(QMouseEvent *event)
{
    qDebug("MoveableWidget::mousePressEvent: x=%d, y=%d\n", event->x(), event->y());

    if (event->button() == Qt::LeftButton)
    {
        m_pointClickPos = event->pos();
        m_bCanMove = true;
    }
}
void MoveableWidget::mouseMoveEvent(QMouseEvent *event)
{
    qDebug("MoveableWidget::mouseMoveEvent: x=%d, y=%d\n", event->x(), event->y());

    if (m_bCanMove && (event->buttons() == Qt::LeftButton))
    {
        QPoint diff = event->pos() - m_pointClickPos;
        qDebug("diff(%d, %d)\n", diff.x(), diff.y());

        QPoint ptMove = mapToParent(diff);
        qDebug("move(%d, %d)\n", ptMove.x(), ptMove.y());

        move(ptMove);
    }
}
void MoveableWidget::mouseReleaseEvent(QMouseEvent *event)
{
    qDebug("MoveableWidget::mouseMoveEvent: x=%d, y=%d\n", event->x(), event->y());
    m_bCanMove = false;
}

bool MoveableWidget::event(QEvent *e)
{
    if (   e->type() == QEvent::HoverEnter 
        || e->type() == QEvent::HoverLeave
        || e->type() == QEvent::HoverMove   )
    {
        QHoverEvent* pHoverEvent = static_cast<QHoverEvent *>(e);

        const char* pType = "QEvent::HoverMove";
        if (e->type() == QEvent::HoverEnter)
        {
            pType = "QEvent::HoverEnter";
        }else if (e->type() == QEvent::HoverLeave)
        {
            pType = "QEvent::HoverLeave";
        }

        qDebug("type=%s (%d, %d)\n", pType, pHoverEvent->pos().x(), pHoverEvent->pos().y());
    }

    return QWidget::event(e);
}
